package com.lsh.service.Impl;

import com.lsh.model.SysPermission;
import com.lsh.model.SysRole;
import com.lsh.model.SysRolePermission;
import com.lsh.service.SysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/11/10 5:33 下午
 * @desc ： 对接口方法的更细粒度的角色权限控制
 */
@Component
public class MyPermissionEvaluatorImpl implements PermissionEvaluator {
    @Autowired
    SysService sysService;


    /**
     * @param authentication 认证过的信息
     * @param targetUrl   要访问的目标路径
     * @param targetPermission   要访问的目标路径需要的权限
     * @return
     */

    @Override
    public boolean hasPermission(Authentication authentication, Object targetUrl, Object targetPermission) {
        System.out.println("目标 url : "+targetUrl);
        System.out.println("目标 权限 : "+targetPermission);
        // 获得loadUserByUsername()方法的结果
        // User是org.springframework.security.core.userdetails.User
        // 是Userdetails的实现类
        User user = (User)authentication.getPrincipal();
        // 获得loadUserByUsername()中注入的角色
        Collection<GrantedAuthority> authorities = user.getAuthorities();
        // 遍历登录用户中所有角色
        for (GrantedAuthority authority : authorities) {
            //1. 获得角色名称  RoleName
            String roleName = authority.getAuthority();
            //2. 根据角色名查出角色信息并获得角色信息  获得RoleId
            SysRole role = sysService.findRoleIdBuRoleName(roleName);
            //3. 再根据角色ID查询角色权限中间表 对应的权限ID   一对多关系：一个RoleID对应多个PermissionId  返回集合
            List<SysRolePermission> permissionsIdByRoleId = sysService.findSysRolePermissionByRoleId(role.getId());
            System.out.println(permissionsIdByRoleId);
            for (SysRolePermission sysRolePermission : permissionsIdByRoleId) {
                //4. 再根据权限ID查询权限信息  是一对一关系   一个权限id只对应一个权限信息
                SysPermission sysPermission = sysService.findPermissionByPermessionId(sysRolePermission.getPermissionId());
                System.out.println("角色是："+roleName+"--对应的权限是："+sysPermission);
                if (targetUrl.equals(sysPermission.getUrl()) && targetPermission.equals(sysPermission.getPermission())){
                    System.out.println("权限校验成功");
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String s, Object o) {
        return false;
    }
}
